<script setup lang='ts'>
import type { PlusColumn } from 'plus-pro-components'
import type { VxeGridProps } from 'vxe-table'

import PublishError from '@/purchase-pages/pricing-tool/add-or-edit-pricing/components/publish-error.vue'
import { useDeleteProject, useDoPubilc, useGetProjectPage } from '@fl/api/purchase'
import { SearchForm, SearchTable } from '@fl/components'
import { useMessage } from '@fl/hooks/web/use-message'
import { treeFindLabel } from '@fl/utils/tree'
import { cloneDeep } from 'lodash-es'

import AddProject from './components/add-project.vue'
import { PRICING_PROJECT_STATUS, PRICING_PROJECT_STATUS_MAP } from './constant'

defineOptions({
    // eslint-disable-next-line vue/component-definition-name-casing
    name: '/purchase-pages/pricing-tool/project-management',
})

const { createConfirmModal } = useMessage()
const router = useRouter()

const showAddProject = ref<boolean>(false)
const showPublishError = ref<boolean>(false)
const errorData = ref<any>({})
const detail = ref<any>({})

const initialState = {
    goodsCategory: '',
    productName: '',
}
const state = ref(cloneDeep(initialState))

const searchConditions = ref(cloneDeep(initialState))
const tablePage = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
})
const getProjectPageParams = computed(() => ({
    ...searchConditions.value,
    pageNum: tablePage.currentPage,
    pageSize: tablePage.pageSize,
}))

const {
    data: productPageData,
    isLoading: isGetProductPageLoading,
    total: productTotal,
} = useGetProjectPage(getProjectPageParams)
const { mutate: deleteProject } = useDeleteProject()

// #region Form
const isFormLoading = computed(() => false)

const columns: PlusColumn[] = [
    {
        colProps: {
            span: 6,
        },
        label: '项目名称',
        prop: 'projectName',
        valueType: 'copy',
    },
]

function submit() {
    searchConditions.value = cloneDeep(state.value)
    resetTablePage()
}

function reset() {
    state.value = cloneDeep(initialState)
    searchConditions.value = cloneDeep(initialState)
    resetTablePage()
}

function resetTablePage() {
    tablePage.currentPage = 1
    tablePage.pageSize = 10
}
// #endregion

// #region Table
const isTableLoading = computed(() => isGetProductPageLoading.value)
const tableData = ref<any[]>([])

const gridOptions = reactive<VxeGridProps>({
    columns: [
        { title: '序号', type: 'seq', width: 60 },
        { field: 'projectName', slots: { default: 'project_name' }, title: '项目名称' },
        { field: 'enterpriseName', title: '招标单位' },
        { field: 'createTime', title: '创建日期', width: 170 },
        { field: 'publishDate', title: '发布日期', width: 170 },
        { field: 'endTime', title: '投标截止时间', width: 170 },
        { field: 'status', slots: { default: 'status' }, title: '状态', width: 100 },
        { slots: { default: 'operation' }, title: '操作', width: 270 },
    ],
})

watchEffect(() => {
    tableData.value = cloneDeep(productPageData.value)
    tablePage.total = productTotal.value
})
// #endregion

// #region UI Listener
function onProjectNameClick(row: any) {
    if (row.status === PRICING_PROJECT_STATUS_MAP.PUBLISHED) {
        onCheckDetailBtnClick(row)
    }
    else {
        onAddProductBtnClick(row)
    }
}

function onEditBtnClick(row: any) {
    detail.value = cloneDeep(row)
    showAddProject.value = true
}

function onCheckDetailBtnClick(row: any) {
    router.push({ path: '/purchase-pages/pricing-tool/project-price-list', query: { projectId: row.id, type: 'see' } })
}

function onAddProductBtnClick(row: any) {
    router.push({ path: '/purchase-pages/pricing-tool/project-price-list', query: { projectId: row.id } })
}

function onChooseSupplierBtnClick(row: any) {
    router.push({ path: '/purchase-pages/pricing-tool/choose-supplier', query: { projectId: row.id, projectName: row.projectName } })
}

const { mutate: mutatePublic } = useDoPubilc()
function onPublishBtnClick(row: any) {
    createConfirmModal({
        content: '确定要发布该招标项目吗？',
        onSuccess: () => {
            mutatePublic(row.id, {
                onSuccess() {
                    ElMessage.success('操作成功')
                },
            })
        },
        title: '提示',
    })
}

function onDeleteBtnClick(row: any) {
    createConfirmModal({
        content: '确定要删除该招标项目吗？',
        onSuccess: () => {
            deleteProject(row.id, {
                onSuccess() {
                    ElMessage.success('操作成功')
                },
            })
        },
        title: '提示',
    })
}

function onAddBtnClick() {
    detail.value = {}
    showAddProject.value = true
}
// #endregion
</script>

<template>
    <el-card mb-20
             shadow="never"
    >
        <el-skeleton v-if="isFormLoading"
                     animated
        />

        <SearchForm v-else
                    v-model="state"
                    :columns="columns"
                    submit-text="查询"
                    :row-props="{ gutter: 40 }"
                    @submit="submit"
                    @reset="reset"
        />
    </el-card>

    <el-card shadow="never">
        <SearchTable v-bind="gridOptions"
                     v-model:pager="tablePage"
                     :loading="isTableLoading"
                     :data="tableData"
        >
            <template #operation="{ row }">
                <template v-if="row.status === PRICING_PROJECT_STATUS_MAP.PUBLISHED">
                    <el-button text
                               type="primary"
                               class="!p-4"
                               @click="onCheckDetailBtnClick(row)"
                    >
                        查看
                    </el-button>

                    <el-button text
                               class="!p-4 !text-[#86909C]"
                               @click="onChooseSupplierBtnClick(row)"
                    >
                        供应商选取
                    </el-button>
                </template>

                <template v-else>
                    <el-button text
                               type="primary"
                               class="!p-4"
                               @click="onEditBtnClick(row)"
                    >
                        修改
                    </el-button>

                    <el-button text
                               class="!p-4 !text-[#86909C]"
                               @click="onPublishBtnClick(row)"
                    >
                        发布
                    </el-button>

                    <el-button text
                               class="!p-4 !text-[#86909C]"
                               @click="onAddProductBtnClick(row)"
                    >
                        添加组合商品
                    </el-button>
                </template>

                <el-button text
                           class="!p-4 !text-[#86909C]"
                           @click="onDeleteBtnClick(row)"
                >
                    删除
                </el-button>
            </template>

            <template #toolbar_buttons>
                <el-space class="mb-12">
                    <el-button type="primary"
                               @click="onAddBtnClick"
                    >
                        <div class="i-ic:baseline-add size-16" />
                        新建
                    </el-button>
                </el-space>
            </template>

            <template #project_name="{ row }">
                <span class="text-#409EFF truncate cursor-pointer"
                      @click="onProjectNameClick(row)"
                >
                    {{ row.projectName }}
                </span>
            </template>

            <template #status="{ row }">
                <span class="px-8 inline-block border-1 rounded-[3px] border-solid text-[12px]"
                      :class="row.status === PRICING_PROJECT_STATUS_MAP.PUBLISHED ? ['bg-[#E3F9E9]', 'border-[#2BA471]', 'text-[#2BA471]'] : ['bg-[#FFF1E9]', 'border-[#E37318]', 'text-[#E37318]']"
                >
                    {{ treeFindLabel({ targetValue: row.status, treeData: PRICING_PROJECT_STATUS }) }}
                </span>
            </template>
        </SearchTable>
    </el-card>

    <AddProject v-model:visible="showAddProject"
                :detail="detail"
    />

    <PublishError v-model:visible="showPublishError"
                  :error-data="errorData"
    />
</template>
